package com.cipta.lomob;

import org.json.JSONObject;

import com.cipta.lomob.model.Users;
import com.facebook.Session;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;

public class LomobManager {
	private static LomobManager instance;
	private JSONObject user;
	private Users userItem;
	
	private final String KEY = "lomob";

	private LomobManager() {
		user = new JSONObject();
	}

	public static LomobManager getInstance() {
		if (instance == null) {
			instance = new LomobManager();
		}

		return instance;
	}

	public JSONObject getUser() {
		return user;
	}

	public JSONObject getUser(Context iContext) {
		try {
			SharedPreferences preferences = iContext.getSharedPreferences(KEY,
					Context.MODE_PRIVATE);
			String iUser = preferences.getString("user", "");
			if (iUser.equalsIgnoreCase(""))
				return null;
			user = new JSONObject(iUser);
			userItem = new Users();
			userItem.setName(user.optString("firstname") + user.optString("lastname"));
			userItem.setAvatar(user.optString("avatar"));
			return user;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	
	public Users getUserItem(){
		return this.userItem;
	}

	public void setUser(Context iContext, JSONObject user) {
		this.user = user;
		saveUser(iContext);
	}

	public void saveUser(Context iContext) {
		SharedPreferences preferences = iContext.getSharedPreferences(KEY,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("user", user.toString());
		editor.commit();
	}

	public void showDialog(Context iContext, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(iContext);
		builder.setMessage(message);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		builder.show();
	}
	
	//administration function
	
	public void logout(Context iContext){
		//clear facebook session
		Session session = Session.getActiveSession();
		session.closeAndClearTokenInformation();
		//now remove user data
		SharedPreferences preferences = iContext.getSharedPreferences(KEY,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.remove("user");
		editor.commit();
	}

}
